// const { defineConfig } = require('@vue/cli-service')
// module.exports = defineConfig({
//   transpileDependencies: true,
//   pages: {
//     index: {
//       entry: 'examples/main.js'
//     }
//   }
// })

/**
 * @description: 开发环境配置
 */

import { readdirSync, statSync } from 'fs'
import { join } from 'path'
import path from 'path'
const __dirname = path.resolve()
// console.log('__dirname :', __dirname)

/**
 * 将给定的目录路径与当前执行脚本的目录路径进行合并
 * @param {string} dir - 当前目录的相对路径
 * @returns 返回一个完整的路径字符串
 */
function resolve(dir) {
  return join(__dirname, dir)
}

function getEntries(path) {
  const files = readdirSync(resolve(path))
  // console.log('files :', files) // files : [ 'index.js', 'testA', 'testB' ]
  const entries = files.reduce((ret, cur) => {
    // * 路径 packages\index.js  packages\testA packages\testB
    const totalPath = join(path, cur)

    // * 检测是不是文件夹 是文件夹 就返回true 不是就false
    const isDir = statSync(totalPath).isDirectory()

    if (isDir) {
      ret[cur] = resolve(join(totalPath, 'index.js'))
      // console.log('ret[cur] :', ret[cur])
    } else {
      const name = cur.split('.')[0]
      ret[name] = resolve(totalPath)
    }
    return ret
  }, {})
  return entries
}

// # 开发和生产环境配置

const DEV_CONFIG = {
  pages: {
    index: {
      entry: './examples/main.js',
    },
  },
  configureWebpack: {
    resolve: {
      extensions: ['.js', '.vue', '.json'],
      alias: {
        '@': resolve('packages'),
      },
    },
  },
}
const BUILD_CONFIG = {
  chainWebpack: config => {
    config.module.rule('js').include.add('/packages').end()
    config.entryPoints.delete('app')
    config.optimization.delete('splitChunks')
    config.plugins.delete('copy')
    config.plugins.delete('html')
    config.plugins.delete('preload')
    config.plugins.delete('prefetch')
    config.plugins.delete('hmr')
  },
  configureWebpack: {
    entry: {
      ...getEntries('packages'),
    },
    output: {
      filename: '[name]/index.js',
      // 各个入口文件打包后的值将会赋值给 module.exports，也意味打包出来的文件将用于 CommonJS 环境 。
      libraryTarget: 'commonjs2',
    },
  },
  outputDir: 'lib',
  css: {
    extract: {
      filename: 'style/[name].css',
    },
  },
  productionSourceMap: false,
}

export default process.env.NODE_ENV === 'development'
  ? DEV_CONFIG
  : BUILD_CONFIG
